package org.liang.code.utils.jms;

import jakarta.jms.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.jms.client.ActiveMQMessage;

import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
/*
  公共配置类
 */
public class JMSCommons {
    // 计数器
    public static AtomicInteger counter = new AtomicInteger(1);
    // CORE的地址
    public static final String CORE_URL = "tcp://127.0.0.1:61616";
    // 账号
    public static final String USERNAME = "liang";
    // 密码
    public static final String PASSWORD = "liang1997";

    // CORE的队列
    public static final String CORE_QUEUE = "core_queue";
    // CORE的主题
    public static final String CORE_TOPIC = "core_topic";
    // 过期消息队列
    public static final String EXPIRYQUEUE = "ExpiryQueue";
    // 死信队列
    public static final String DLQ = "DLQ";


    // 高级队列和主题
    // 最后值队列 topic同理
    public static final String CORE_LVQ = "core_lvq?last-value=true";
    // 非破坏性队列 topic同理
    public static final String CORE_NDQ = "core_ndq?non-destructive=true";
    // 环形队列 topic同理
    public static final String CORE_RINGQ = "core_ringq?ring-size=4";
    // 追溯地址
    public static final String CORE_RMCT = "core_rmct?retroactive-message-count=5";
    // 独占队列 topic同理 同一时间只能有一个消费者 连接 消费 保证消息的顺序性
    public static final String CORE_DEQ = "core_deq?exclusive=true";

    //消费者优先 topic同理 优先级值的范围是 -2的31次方到 2的31次方 -1
    public static final String CORE_CPQA = "core_cpq?consumer-priority=50";
    public static final String CORE_CPQB = "core_cpq?consumer-priority=100";


    /**
     * 读取消息
     * @param consumer JMS 消费者
     */
    public static void readMessage(JMSConsumer consumer) throws JMSException {
        Message me = consumer.receive();
        ClientMessage coreMessage = ((ActiveMQMessage) me).getCoreMessage();
        long messageID = coreMessage.getMessageID();
        if (me instanceof TextMessage textMessage) {
            String text;
            try {
                text = textMessage.getText();
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
            log.info("messageID:{}, type is TextMessage, body:{}", messageID, text);
        } else if (me instanceof BytesMessage bytesMessage) {
            try {
                log.info("messageID:{}, type is BytesMessage, bodyLenth:{}", messageID, bytesMessage.getBodyLength());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        } else if (me instanceof MapMessage) {
            log.info("messageID:{}, type is MapMessage", messageID);
        } else if (me instanceof ObjectMessage) {
            log.info("messageID:{}, type is ObjectMessage", messageID);
        } else if (me instanceof StreamMessage) {
            log.info("messageID:{}, type is StreamMessage", messageID);
        } else {
            log.info("messageID:{}, type is Message", messageID);
        }
    }
}
